<template>
  <div class="word-training">
    <div class="word-training__container">
      <!-- 左侧单元列表 -->
      <div class="word-training__sidebar">
        <div class="unit-list">
          <div
            v-for="unit in unitList"
            :key="unit.id"
            class="unit-item"
            :class="{ 'is-active': activeShowUnit?.id === unit.id }"
            @click="handleUnitClick(unit)"
          >
            {{ unit.name }}
          </div>
        </div>
      </div>

      <!-- 右侧学习类型卡片 -->
      <div class="word-training__main">
        <!-- 主内容区顶部重学按钮，右对齐 -->
        <div
          style="
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
          "
        >
          <el-button type="default" @click="handleBack">返回</el-button>
          <el-button
            type="warning"
            @click="showResetDialog = true"
            :disabled="!currentUnitStudyStats"
            >重学</el-button
          >
        </div>
        <template v-if="currentUnitStudyStats">
          <div class="study-cards">
            <!-- 智能记忆卡片 -->
            <el-card class="study-card" @click="handleStudyClick('znjy')">
              <template #header>
                <div class="study-card__header">
                  <span class="study-card__title">智能记忆</span>
                  <el-tag
                    :type="
                      currentUnitStudyStats.isEndZnjy === 1 ? 'success' : 'info'
                    "
                    size="small"
                  >
                    {{
                      currentUnitStudyStats.isEndZnjy === 1
                        ? '已完成学习'
                        : '开始学习'
                    }}
                  </el-tag>
                </div>
              </template>
              <div class="study-card__content">
                <div class="study-info">
                  <div class="info-item">
                    <span class="label">单词数量：</span>
                    <span class="value">{{
                      currentUnitStudyStats.unitTotal
                    }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">已学个数：</span>
                    <span class="value">{{
                      currentUnitStudyStats.studyNumZnjy
                    }}</span>
                  </div>
                  <div v-if="currentUnitStudyStats.isEndZnjy === 1">
                    <div class="info-item">
                      <span class="label">学习用时：</span>
                      <span class="value">{{
                        currentUnitStudyStats.testTimeZnjy
                      }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">需复习个数：</span>
                      <span class="value">{{
                        currentUnitStudyStats.restudyNumZnjy
                      }}</span>
                    </div>
                    <div
                      class="info-item score-item"
                      v-if="currentUnitStudyStatus?.memoryScore"
                    >
                      <span class="label">学习得分：</span>
                      <span class="value score-value"
                        >{{ currentUnitStudyStatus.memoryScore }}分</span
                      >
                    </div>
                  </div>
                </div>
              </div>
            </el-card>

            <!-- 智能听写卡片 -->
            <el-card class="study-card" @click="handleStudyClick('zntx')">
              <template #header>
                <div class="study-card__header">
                  <span class="study-card__title">智能听写</span>
                  <el-tag
                    :type="
                      currentUnitStudyStats.isEndZntx === 1 ? 'success' : 'info'
                    "
                    size="small"
                  >
                    {{
                      currentUnitStudyStats.isEndZntx === 1
                        ? '已完成学习'
                        : '开始学习'
                    }}
                  </el-tag>
                </div>
              </template>
              <div class="study-card__content">
                <div class="study-info">
                  <div class="info-item">
                    <span class="label">单词数量：</span>
                    <span class="value">{{
                      currentUnitStudyStats.unitTotal
                    }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">已学个数：</span>
                    <span class="value">{{
                      currentUnitStudyStats.studyNumZntx
                    }}</span>
                  </div>
                  <div v-if="currentUnitStudyStats.isEndZntx === 1">
                    <div class="info-item">
                      <span class="label">学习用时：</span>
                      <span class="value">{{
                        currentUnitStudyStats.testTimeZntx
                      }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">需复习个数：</span>
                      <span class="value">{{
                        currentUnitStudyStats.restudyNumZntx
                      }}</span>
                    </div>
                    <div
                      class="info-item score-item"
                      v-if="currentUnitStudyStatus?.dictationScore"
                    >
                      <span class="label">学习得分：</span>
                      <span class="value score-value"
                        >{{ currentUnitStudyStatus.dictationScore }}分</span
                      >
                    </div>
                  </div>
                </div>
              </div>
            </el-card>

            <!-- 智能默写卡片 -->
            <el-card class="study-card" @click="handleStudyClick('znmx')">
              <template #header>
                <div class="study-card__header">
                  <span class="study-card__title">智能默写</span>
                  <el-tag
                    :type="
                      currentUnitStudyStats.isEndZnmx === 1 ? 'success' : 'info'
                    "
                    size="small"
                  >
                    {{
                      currentUnitStudyStats.isEndZnmx === 1
                        ? '已完成学习'
                        : '开始学习'
                    }}
                  </el-tag>
                </div>
              </template>
              <div class="study-card__content">
                <div class="study-info">
                  <div class="info-item">
                    <span class="label">单词数量：</span>
                    <span class="value">{{
                      currentUnitStudyStats.unitTotal
                    }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">已学个数：</span>
                    <span class="value">{{
                      currentUnitStudyStats.studyNumZnmx
                    }}</span>
                  </div>
                  <div v-if="currentUnitStudyStats.isEndZnmx === 1">
                    <div class="info-item">
                      <span class="label">学习用时：</span>
                      <span class="value">{{
                        currentUnitStudyStats.testTimeZnmx
                      }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">需复习个数：</span>
                      <span class="value">{{
                        currentUnitStudyStats.restudyNumZnmx
                      }}</span>
                    </div>
                    <div
                      class="info-item score-item"
                      v-if="currentUnitStudyStatus?.writingScore"
                    >
                      <span class="label">学习得分：</span>
                      <span class="value score-value"
                        >{{ currentUnitStudyStatus.writingScore }}分</span
                      >
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </template>
        <template v-else>
          <div class="study-cards">
            <!-- 智能记忆卡片 -->
            <el-card class="study-card" @click="handleStudyClick('znjy')">
              <template #header>
                <div class="study-card__header">
                  <span class="study-card__title">智能记忆</span>
                  <el-tag type="info" size="small">开始学习</el-tag>
                </div>
              </template>
              <div class="study-card__content">
                <div class="study-info">
                  <div class="info-item">
                    <span class="label">单词数量：</span>
                    <span class="value">{{ getCurrentUnitWordCount() }}</span>
                  </div>
                  <div
                    class="info-item score-item"
                    v-if="currentUnitStudyStatus?.memoryScore"
                  >
                    <span class="label">学习得分：</span>
                    <span class="value score-value"
                      >{{ currentUnitStudyStatus.memoryScore }}分</span
                    >
                  </div>
                </div>
              </div>
            </el-card>

            <!-- 智能听写卡片 -->
            <el-card class="study-card" @click="handleStudyClick('zntx')">
              <template #header>
                <div class="study-card__header">
                  <span class="study-card__title">智能听写</span>
                  <el-tag type="info" size="small">开始学习</el-tag>
                </div>
              </template>
              <div class="study-card__content">
                <div class="study-info">
                  <div class="info-item">
                    <span class="label">单词数量：</span>
                    <span class="value">{{ getCurrentUnitWordCount() }}</span>
                  </div>
                  <div
                    class="info-item score-item"
                    v-if="currentUnitStudyStatus?.dictationScore"
                  >
                    <span class="label">学习得分：</span>
                    <span class="value score-value"
                      >{{ currentUnitStudyStatus.dictationScore }}分</span
                    >
                  </div>
                </div>
              </div>
            </el-card>

            <!-- 智能默写卡片 -->
            <el-card class="study-card" @click="handleStudyClick('znmx')">
              <template #header>
                <div class="study-card__header">
                  <span class="study-card__title">智能默写</span>
                  <el-tag type="info" size="small">开始学习</el-tag>
                </div>
              </template>
              <div class="study-card__content">
                <div class="study-info">
                  <div class="info-item">
                    <span class="label">单词数量：</span>
                    <span class="value">{{ getCurrentUnitWordCount() }}</span>
                  </div>
                  <div
                    class="info-item score-item"
                    v-if="currentUnitStudyStatus?.writingScore"
                  >
                    <span class="label">学习得分：</span>
                    <span class="value score-value"
                      >{{ currentUnitStudyStatus.writingScore }}分</span
                    >
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </template>
      </div>
    </div>
    <!-- 重学弹窗 -->
    <el-dialog v-model="showResetDialog" title="重学模块重置" width="400px">
      <el-checkbox-group v-model="resetModules">
        <el-checkbox
          label="znjy"
          :disabled="currentUnitStudyStats?.isEndZnjy !== 1"
          >智能记忆</el-checkbox
        >
        <el-checkbox
          label="zntx"
          :disabled="currentUnitStudyStats?.isEndZntx !== 1"
          >智能听写</el-checkbox
        >
        <el-checkbox
          label="znmx"
          :disabled="currentUnitStudyStats?.isEndZnmx !== 1"
          >智能默写</el-checkbox
        >
      </el-checkbox-group>
      <template #footer>
        <el-button @click="showResetDialog = false">取消</el-button>
        <el-button
          type="primary"
          :disabled="resetModules.length === 0"
          @click="handleReset"
          >重置</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  // useDcyxSeriesStore,
  useDcyxProgramStore,
  useDcyxUnitStore,
  useDcyxUserStoreHook,
} from '@/store'
import type {
  UnitStudyStatsItem,
  UnitStudyStatusItem,
} from '@/api/dcyx/units.api'
import type { UnitItem } from '@/api/dcyx/units.api'
import { useRouter } from 'vue-router'

// const dcyxSeriesStore = useDcyxSeriesStore()
const dcyxProgramStore = useDcyxProgramStore()
const dcyxUnitStore = useDcyxUnitStore()
const router = useRouter()

// 返回dashboard主页
const handleBack = () => {
  router.push('/')
}

const currentProgram = computed(() => dcyxProgramStore.currentProgram)
const unitList = ref<UnitItem[]>([])
const currentUnit = ref<UnitItem>({} as UnitItem)
const currentUnitStudyStats = ref<UnitStudyStatsItem>()
const currentUnitStudyStatus = ref<UnitStudyStatusItem>()
const activeShowUnit = ref<UnitItem>()
const showResetDialog = ref(false)
const resetModules = ref<string[]>([])

// 获取单元列表
const fetchUnitList = async () => {
  try {
    // TODO: 调用 API 获取单元列表
    // const { data } = await getUnitsByProgram(seriesId, programId)
    // unitList.value = data
    const units = await dcyxUnitStore.getUnitsByProgramId({
      programId: Number(currentProgram.value?.programId),
      pageNum: 1,
      pageSize: 100,
    })
    unitList.value = units
    // 默认选中第一个单元
    currentUnit.value = units[0]
  } catch {
    ElMessage.error('获取单元列表失败')
  }
}

// 获取当前单元的单词数量
const getCurrentUnitWordCount = () => {
  if (!activeShowUnit.value) return 0
  return activeShowUnit.value.totalNum || 0
}

// 获取单元详情
const fetchUnitInfo = async (_unitId: number) => {
  if (!_unitId) return
  try {
    currentUnitStudyStats.value = await dcyxUnitStore.getUnitStudyStats(_unitId)
  } catch {
    ElMessage.error('获取单元详情失败')
  }
  // 获取单元学习状态
  try {
    currentUnitStudyStatus.value =
      await dcyxUnitStore.getUnitStudyStatus(_unitId)
  } catch {
    ElMessage.error('获取单元学习状态失败')
  }
}

// 处理单元点击
const handleUnitClick = (unit: UnitItem) => {
  // dcyxProgramStore.currentUnit = unit
  activeShowUnit.value = unit
  // currentUnit.value = unit
  fetchUnitInfo(unit.id)
}

// 处理学习类型点击
// 更新选择的单元
const handleStudyClick = async (type: 'znjy' | 'zntx' | 'znmx') => {
  if (!activeShowUnit.value) return

  // 如果存在学习统计信息，检查是否已完成
  if (currentUnitStudyStats.value) {
    if (
      (type === 'znjy' && currentUnitStudyStats.value.isEndZnjy === 1) ||
      (type === 'zntx' && currentUnitStudyStats.value.isEndZntx === 1) ||
      (type === 'znmx' && currentUnitStudyStats.value.isEndZnmx === 1)
    ) {
      return
    }
  }

  const typeMap = {
    znjy: '/dcyx/inteli-memory',
    zntx: '/dcyx/inteli-dictation',
    znmx: '/dcyx/inteli-writing',
  }

  const userId = useDcyxUserStoreHook().userInfo.id
  await dcyxUnitStore.updateCurrentUnit({
    unitId: Number(activeShowUnit.value?.id),
    userId: Number(userId),
  })
  // }
  // 再查询一次当前单元
  await dcyxUnitStore.getCurrentUnit()
  router.push(typeMap[type])
}

// 重置学习模块
const handleReset = async () => {
  if (!currentUnitStudyStats.value || resetModules.value.length === 0) return

  try {
    await resetSelectedModules()
    await resetUnitStudyStatus()

    ElMessage.success('重置成功')
    showResetDialog.value = false
    resetModules.value = []

    // 刷新当前单元信息
    await fetchUnitInfo(currentUnitStudyStats.value.unitId)
  } catch (error) {
    ElMessage.error('重置失败')
    console.error('重置失败:', error)
  }
}

// 重置选中的学习模块统计信息
const resetSelectedModules = async () => {
  const stats = currentUnitStudyStats.value!
  const payload = createResetPayload(stats)

  await dcyxUnitStore.updateUnitStudyStats(payload)
}

// 创建重置数据载荷
const createResetPayload = (stats: UnitStudyStatsItem) => {
  const payload: any = {
    userId: Number(stats.userId),
    unitId: Number(stats.unitId),
    unitTotal: stats.unitTotal,
    // 保持原有数据
    studyNumZnjy: stats.studyNumZnjy,
    studyNumZnmx: stats.studyNumZnmx,
    studyNumZntx: stats.studyNumZntx,
    testTimeZnjy: stats.testTimeZnjy,
    testTimeZnmx: stats.testTimeZnmx,
    testTimeZntx: stats.testTimeZntx,
    restudyNumZnjy: stats.restudyNumZnjy,
    restudyNumZnmx: stats.restudyNumZnmx,
    restudyNumZntx: stats.restudyNumZntx,
    isEndZnjy: stats.isEndZnjy,
    isEndZnmx: stats.isEndZnmx,
    isEndZntx: stats.isEndZntx,
  }

  // 重置选中模块的相关字段
  resetModules.value.forEach((module) => {
    const moduleKey = getModuleKey(module)
    payload[`studyNum${moduleKey}`] = 0
    payload[`testTime${moduleKey}`] = 0
    payload[`restudyNum${moduleKey}`] = 0
    payload[`isEnd${moduleKey}`] = 0
  })

  return payload
}

// 获取模块键名
const getModuleKey = (module: string): string => {
  const moduleMap: Record<string, string> = {
    znjy: 'Znjy',
    zntx: 'Zntx',
    znmx: 'Znmx',
  }
  return moduleMap[module] || module
}

// 重置单元学习状态
const resetUnitStudyStatus = async () => {
  if (!currentUnitStudyStatus.value) return

  const unitId = Number(currentUnitStudyStats.value!.unitId)
  const rawStatus = currentUnitStudyStatus.value

  // 并行处理所有选中模块的状态重置
  const resetPromises = resetModules.value.map(async (module) => {
    const statusPayload = createStatusResetPayload(module, unitId, rawStatus)
    await dcyxUnitStore.updateUnitStudyStatus(statusPayload)
  })

  await Promise.all(resetPromises)
}

// 创建状态重置载荷
const createStatusResetPayload = (
  module: string,
  unitId: number,
  rawStatus: UnitStudyStatusItem,
) => {
  const sourceMap: Record<string, number> = {
    znjy: 0, // 智能记忆
    zntx: 1, // 智能听写
    znmx: 2, // 智能默写
  }

  return {
    unitId,
    source: sourceMap[module] || 0,
    // 根据模块类型重置对应字段，保持其他字段不变
    memoryCompleted: module === 'znjy' ? 0 : rawStatus.memoryCompleted || 0,
    memoryScore: module === 'znjy' ? 0 : rawStatus.memoryScore || 0,
    memoryTimeConsuming:
      module === 'znjy' ? 0 : rawStatus.memoryTimeConsuming || 0,
    dictationCompleted:
      module === 'zntx' ? 0 : rawStatus.dictationCompleted || 0,
    dictationScore: module === 'zntx' ? 0 : rawStatus.dictationScore || 0,
    dictationTimeConsuming:
      module === 'zntx' ? 0 : rawStatus.dictationTimeConsuming || 0,
    writingCompleted: module === 'znmx' ? 0 : rawStatus.writingCompleted || 0,
    writingScore: module === 'znmx' ? 0 : rawStatus.writingScore || 0,
    writingTimeConsuming:
      module === 'znmx' ? 0 : rawStatus.writingTimeConsuming || 0,
  }
}

async function initWordTraining() {
  try {
    await dcyxUnitStore.initUnitStore()
    unitList.value = dcyxUnitStore.unitsList

    currentUnit.value.id = dcyxUnitStore.currentUnit.unitId
    currentUnit.value.name = dcyxUnitStore.currentUnit.unitName

    await Promise.all([dcyxProgramStore.initProgramStore()])
    await Promise.all([fetchUnitList(), fetchUnitInfo(currentUnit.value?.id)])
    activeShowUnit.value = currentUnit.value
  } catch {
    ElMessage.error('初始化应用数据失败，请稍后重试')
  }
}

onMounted(() => {
  initWordTraining()
})
</script>

<style lang="scss" scoped>
.word-training {
  height: 100%;
  background-color: var(--el-bg-color-page);
  padding: 12px;

  &__container {
    display: flex;
    gap: 12px;
    height: 100%;
  }

  &__sidebar {
    width: 200px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }

  &__main {
    flex: 1;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    padding: 16px;
  }
}

.unit-list {
  .unit-item {
    padding: 8px 12px;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s;
    border-bottom: 1px solid var(--el-border-color-lighter);

    &:hover {
      background-color: var(--el-color-primary-light-9);
    }

    &.is-active {
      background-color: var(--el-color-primary-light-8);
      color: var(--el-color-primary);
      font-weight: 500;
    }
  }
}

.study-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 12px;
}

.study-card {
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  &__title {
    font-size: 16px;
    font-weight: 500;
  }

  &__content {
    padding: 8px 0;
  }
}

.study-info {
  .info-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;
    font-size: 13px;
    color: var(--el-text-color-regular);

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      color: var(--el-text-color-secondary);
    }

    .value {
      font-weight: 500;
    }

    &.score-item {
      margin-top: 8px;
      padding-top: 8px;
      border-top: 1px solid var(--el-border-color-lighter);

      .score-value {
        font-size: 16px;
        font-weight: 600;
        color: var(--el-color-primary);
      }
    }
  }
}
</style>
